package com.oracle.context.suport;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ClassPathXmlApplicationContext implements BeanFactory {
	private static Map<String,Object> map= new HashMap<String,Object>();
	@SuppressWarnings("unchecked")
	public ClassPathXmlApplicationContext() throws Exception{
//		new ClassPathXmlApplicationContext("applicationContext.xml");
		
//		File file = new File();
//		System.out.println(ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(arg0));
		InputStream in = ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream("applicationContext.xml");
//		System.out.println(in);
		SAXReader reader = new SAXReader();
		Document doc= reader.read(in);
		Element root = doc.getRootElement();
		List<Element> elements = (List<Element>)root.elements();
		for(Element element:elements){
			Object obj = Class.forName(element.attributeValue("class")).newInstance();
			map.put(element.attributeValue("name"), obj);
			Element subElement = element.element("property");
			if(subElement!=null){
//				System.out.println(subElement.attributeValue("name")+":"+subElement.attributeValue("ref"));
//				map.put(subElement.attributeValue("name"), map.get(subElement.attributeValue("ref")));
				Field field = obj.getClass().getDeclaredField(subElement.attributeValue("name"));
				String setMethodName = "set"+field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1);
				Method method = obj.getClass().getDeclaredMethod(setMethodName, field.getType());
				method.invoke(obj, map.get(subElement.attributeValue("ref")));
			}
		}
		for(Map.Entry<String, Object> entry:map.entrySet()){
			System.out.println(entry.getKey()+":"+entry.getValue());
		}
		
		
	}
	public ClassPathXmlApplicationContext(String path){
		
	}
	
	@Override
	public Object getBean(String beanName) {
		return map.get(beanName);
	}
	public static void main(String[] args) throws Exception {
		new ClassPathXmlApplicationContext();
	}

}
